package com.study.springboot.controller;

import com.study.springboot.client.DepartClient;
import com.study.springboot.dto.Depart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author huyong
 * @Decription
 * @date 2025-03-05 16:58
 */
@RestController
@RequestMapping("api/v1/consumer/depart")
public class DepartController {
    @Autowired
    private DepartClient departClient;
    /**
     * 用于发现服务
     */
    @Autowired
    private DiscoveryClient discoveryClient;
    /**
     * 使用ip直连
     */
    //private static final String SERVICE_PROVIDER_URL = "http://127.0.0.1:8081/ap1/v1/provicer/depart";
    /**
     * 使用注册中心 用服务名称调用
     */
    private static final String SERVICE_PROVIDER_URL = "http://provider/ap1/v1/provicer/depart";

    @GetMapping(path = "/{id}", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Depart getDepartById(@PathVariable("id") Integer id) {
        return departClient.getDepartById(id);
    }

    @PostMapping
    public boolean saveDepart(@RequestBody Depart depart) {
        return departClient.saveDepart(depart);
    }

    @PutMapping
    public boolean modifyDepart(@RequestBody Depart depart) {
        return departClient.saveDepart(depart);
    }

    @DeleteMapping("/{id}")
    public boolean removeDepartById(@PathVariable("id") Integer id) {
        return departClient.deleteDepartById(id);
    }

    @GetMapping
    @ResponseBody
    public List<Depart> getAllDeparts() {
        return departClient.getAllDeparts();
    }

    @GetMapping("/discovery")
    public String discovery() {
        //获取注册中心所有的服务名称
        List<String> services = discoveryClient.getServices();
        for (String serviceName : services) {
            //获取指定微服务名称的所有微服务实例  集群
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
            for (ServiceInstance instance : instances) {
                System.out.println(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
            }
        }
        return "success";
    }


    @GetMapping("/port")
    public Map<String, Integer> getPort() {
        return departClient.getPort();
    }

}
